package aop.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * Author：汤小洋
 * Date：2023-07-04 15:14
 * Description：<描述>
 */
@Component
@Aspect // 标记为切面类
public class LogAdvice {

    // 定义切点表达式
    @Pointcut("execution(* aop.service.impl.*.*(..))")
    public void pc(){}

    /**
     * 前置通知
     */
    @Before("pc()")
    public void before(JoinPoint joinPoint) {
        System.out.println("在方法执行前做日志。。。。。。方法名："+joinPoint.getSignature().getName()+"，参数："+ Arrays.toString(joinPoint.getArgs()));
    }

    /**
     * 后置通知
     */
    @AfterReturning(value = "pc()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        System.out.println("在方法执行后做日志。。。。。。方法名："+joinPoint.getSignature().getName()+"，返回值："+result);
    }

    /**
     * 异常通知
     */
    @AfterThrowing(value = "pc()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Exception e) {
        System.out.println("在方法执行异常时做日志。。。。。。方法名："+joinPoint.getSignature().getName()+"，异常："+e.getMessage());
    }

    /**
     * 环绕通知
     */
    @Around("pc()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("在方法执行前开启事务。。。。。。");
        Object result = null;
        try {
            result = joinPoint.proceed();
            System.out.println("在方法执行后提交事务。。。。。。");
        } catch (Throwable e) {
            System.out.println("方法执行失败，回滚事务。。。。。。");
            throw new RuntimeException(e);
        }
        return result;
    }

}
